<?php

namespace MoChat\App\Common\Service;

use App\Constants\Basis\ImageTypeCode;
use App\Exception\ValidatorException;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use think\Image;

class FileUpload
{
    /**
     * 生成名称
     * @return string
     */
    private static function generateName()
    {
        return md5(time() . uniqid(rand(), true));
    }

    /**
     * 返回图片地址
     * @param $factory
     * @param $request
     * @return string[]
     */
    public static function upload($factory, $request)
    {
        if (!$request->hasFile('file')) {
            throw new CommonException(ErrorCode::AUTH_UNAUTHORIZED, '请上传图片');
        }
        $file = $request->file('file');
        $extension = strtolower($request->file('file')->getExtension());
        if (!in_array($extension, ['jpeg', 'png', 'jpg'])) {
            throw new ValidatorException('图片格式错误');
        }
        $stream = fopen($file->getRealPath(), 'r+');
        $local = $factory->get('local');
        $path = 'image/' . date("Ymd");

        if (!file_exists(BASE_PATH . '/runtime/image')) {
            @mkdir(BASE_PATH . '/runtime/image', 0777);
        }

        if (!file_exists(BASE_PATH . '/runtime/' . $path)) {
            @mkdir(BASE_PATH . '/runtime/' . $path, 0777);
        }
        if (!file_exists(BASE_PATH . '/runtime/' . $path . '/water/')) {
            @mkdir(BASE_PATH . '/runtime/' . $path . '/water/', 0777);
        }
        if (!file_exists(BASE_PATH . '/runtime/' . $path . '/thumb/')) {
            @mkdir(BASE_PATH . '/runtime/' . $path . '/thumb/', 0777);
        }
        $pathName = $path . '/original/' . self::generateName() . '.' . $extension;
        $local->writeStream($pathName, $stream);
        if (is_resource($stream)) {
            fclose($stream);
        }
        $host = config('basis')['image_host'];
        $images = [];
        switch ($type) {
            //原图
            case ImageTypeCode::ORIGINAL:
                $images = [
                    'original_path' => $pathName,
                    'original_url' => $host . $pathName,//完整路径
                ];
                break;
            //原图
            case ImageTypeCode::WATERMARK:
                $water = Image::open(BASE_PATH . '/runtime/' . $pathName);
                $waterImage = $path . '/water/' . self::generateName() . '.' . $extension;
                $water->thumb(800, 800)->water(BASE_PATH . '/runtime/path/watermark.png', 5, 50)->save(BASE_PATH . '/runtime/' . $waterImage);
                $images = [
                    'water_path' => $waterImage,
                    'water_url' => $host . $waterImage,
                ];
                break;
            //缩略图
            case ImageTypeCode::THUMBNAIL:
                $thumb = Image::open(BASE_PATH . '/runtime/' . $pathName);
                $thumbImage = $path . '/thumb/' . self::generateName() . '.' . $extension;
                $thumb->thumb(360, 360)->save(BASE_PATH . '/runtime/' . $thumbImage);
                $images = [
                    'thumb_path' => $thumbImage,
                    'thumb_url' => $host . $thumbImage,
                ];
                break;
            //所有图
            case ImageTypeCode::ALL_FIGURE:
                $water = Image::open(BASE_PATH . '/runtime/' . $pathName);
                $waterImage = $path . '/water/' . self::generateName() . '.' . $extension;
                $water->thumb(800, 800)->water(BASE_PATH . '/runtime/path/watermark.png', 5, 50)->save(BASE_PATH . '/runtime/' . $waterImage);
                $thumb = Image::open(BASE_PATH . '/runtime/' . $pathName);
                $thumbImage = $path . '/thumb/' . self::generateName() . '.' . $extension;
                $thumb->thumb(360, 360)->save(BASE_PATH . '/runtime/' . $thumbImage);

                $images = [
                    'original_path' => $pathName,
                    'original_url' => $host . $pathName,
                    'water_path' => $waterImage,
                    'water_url' => $host . $waterImage,
                    'thumb_path' => $thumbImage,
                    'thumb_url' => $host . $thumbImage,
                ];
                break;
            default:
                $images = [
                    'original_path' => $pathName,
                    'original_url' => $host . $pathName,//完整路径
                ];
        }
        if (in_array($type, [
            ImageTypeCode::WATERMARK,
            ImageTypeCode::THUMBNAIL
        ])) {
            $url = BASE_PATH . '/runtime/' . $pathName;
            if (file_exists($url)) {
                unlink($url);
            }
        }
        return $images;
    }

    /**
     * 搜索替换掉host
     * @param $url
     * @return array|string
     */
    public static function matchingHost($url)
    {
        $host = config('basis')['image_host'];
        return str_replace($host, '', $url);
    }

    /**
     * 给图片拼接上host
     * @param $path
     * @return string
     */
    public static function jointHost($path)
    {
        $host = config('basis')['image_host'];
        return $host . $path;
    }
}
